<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;
class Linkmenu extends Base
{
//前置操作定义
    protected $beforeActionList = [
        // 'second' =>  ['except'=>'hello'],
        'beforeEdit'  =>  ['only'=>'edit,add'],
    ];
    private $mod;
    private $menu_id;
    public function _initialize(){
        parent::_initialize();
        $this->mod = model('linkmenu');
        $this->menu_id = input('param.menu_id/d');

    }
    public function index() {
        $sort  = input("param.sort", 'ordid');
        $order = input("param.order",'ASC');
        $tree = new \org\Tree();
        $tree->icon = ['│ ','├─ ','└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $result = $this->mod->where('menuid',$this->menu_id)->order($sort . ' ' . $order)->select();
        $result = objToArray($result);
        $array = [];
        foreach($result as $r) {
            $r['str_status'] = '<img data-tdtype="toggle" data-id="'.$r['id'].'" data-field="status" data-value="'.$r['status'].'" src="/static/manage/images/toggle_' . ($r['status'] == 0 ? 'disabled' : 'enabled') . '.gif" />';
            $r['str_manage'] = '<a href="javascript:;" class="J_showdialog" data-uri="'.url('Linkmenu/add',['pid'=>$r['id'],'menu_id'=>$this->menu_id]).'" data-title="添加子栏目" data-id="add" data-width="500" data-height="360">添加子栏目</a> |
                                <a href="javascript:;" class="J_showdialog" data-uri="'.url('Linkmenu/edit',['id'=>$r['id'],'menu_id'=>$this->menu_id]).'" data-title="编辑-'. $r['name'] .'" data-id="edit" data-width="500" data-height="360">编辑</a> |
                                <a href="javascript:;" class="J_confirmurl" data-acttype="ajax" data-uri="'.url('Linkmenu/delete',['id'=>$r['id']]).'" data-msg="'.sprintf('确定要删除么？',$r['name']).'">删除</a>';
            $r['parentid_node'] = ($r['pid'])? ' class="child-of-node-'.$r['pid'].'"' : '';
            $array[] = $r;
        }
        $str  = "<tr id='node-\$id' \$parentid_node>
                <td align='center'><input type='checkbox' value='\$id' class='J_checkitem'></td>
                <td align='center'>\$id</td>
                <td>\$spacer<span data-tdtype='edit' data-field='name' data-id='\$id' class='tdedit'>\$name</span></td>
				<td align='center'>\$alias</td>
                <td align='center'><span data-tdtype='edit' data-field='ordid' data-id='\$id' class='tdedit'>\$ordid</span></td>

                <td align='center'>\$str_status</td>
                <td align='center'>\$str_manage</td>
                </tr>";
        $tree->init($array);
        $list = $tree->get_tree(0, $str);
        $this->assign('list', $list);
        //bigmenu (标题，地址，弹窗ID，宽，高)
        $big_menu = array(
            'title' => '添加栏目',
            'iframe' => url('Linkmenu/add',['menu_id'=>$this->menu_id]),
            'id' => 'add',
            'width' => '500',
            'height' => '360'
        );
        $this->assign('big_menu', $big_menu);
        $this->assign('list_table', true);
        return $this->fetch();
    }
    protected function beforeEdit(){
        $pid = input('param.pid/d');
        $spid = 0;
        if ($pid) {
            $spid = $this->mod->where(['id'=>$pid])->value('spid');
            $spid = $spid ? $spid.$pid : $pid;
        }
        $this->assign('spid', $spid);
        $this->assign('menu_id',$this->menu_id);
    }
    public function addDo(){
        $data = input('post.');
        $name_arr = explode("\n",str_replace('&',"\n",trim($data['name'])));
        $aliasRadio = $data['aliasRadio'];
        unset($data['aliasRadio']);
        $py = new \org\Pinyin();
        $adddata = [];
        foreach($name_arr as $v){
            //检测分类是否存在
            if($this->mod->name_exists($data['name'], $data['pid'])){
                unset($v);
            }else{
                //生成spid
                $data['name'] = trim($v);
                $data['spid'] = $this->mod->get_spid($data['pid']);
                $data['alias']= $aliasRadio == 1 ? trim($py->getFirstPY($data['name'])) : trim($py->getAllPY($data['name']));		//全部拼音
                $adddata[] = $data;
            }
        }
        if($this->mod->saveAll($adddata)){
            $this->ajaxReturn(1,'添加成功','','add');
        }else{
            $this->ajaxReturn(0,'添加失败','','add');
        }

    }
    public function delete(){
        //判断是否有下级栏目存在  存在则不能删除
        \app\common\model\Linkmenu::event('before_delete',function($obj){
            $id = $obj->id;
            //是否有下级栏目
            $child = $this->mod->get_child_ids($id);

            if(!empty($child)){
                return false;
            }
            return true;
        });
        parent::delete();
    }
    public function ajaxGetchilds() {
        $id = input('param.id/d');
        $menu_id = input('param.menuid/d');
        $map['pid'] = $id;
        $menu_id && $map['menuid'] = $menu_id;
        $return = $this->mod->field('id,name')->where($map)->select();
        if ($return) {
            $this->ajaxReturn(1, 'success', $return);
        } else {
            $this->ajaxReturn(0, 'error');
        }
    }
    /**
     * 更新联动菜单缓存
     */
    public function cache(){
        if($this->doCache()){
            $this->success('联动菜单缓存更新成功');
        }else{
            $this->error('联动菜单缓存更新失败');
        }
    }
    public function doCache(){
        $cate  = model('linkmenu_cate');
        $cate_list = $cate->where('status',1)->select();
        if($cate_list){
            foreach($cate_list as $val){
                $lists = $this->mod->field('id,pid,name,alias')->where(['status'=>1,'menuid'=>$val['id']])->select();
                if($lists){
                    $cate = objToArray($lists);//普通列表
                    $temp = [];
                    foreach($cate as $v){
                        $temp[$v['id']] = $v;
                    }
                    $tree = list_to_tree($temp);//树形列表
                    cache('linkmenu_'.$val['id'],['cate'=>$temp,'tree'=>$tree]);
                }
            }
            return true;
        }

        return false;

    }
}